package pers.liyan.shi.providerticket.config;

import org.springframework.boot.context.embedded.EmbeddedServletContainerInitializedEvent;
import org.springframework.context.ApplicationListener;
import org.springframework.stereotype.Component;

/**
 * 通过监听启动事件获取端口
 * springboot 2.x失效
 * 使用以下代码
 *
 * import org.springframework.boot.web.context.WebServerInitializedEvent;
 * import org.springframework.context.ApplicationListener;
 * import org.springframework.stereotype.Component;
 *
 * import java.net.InetAddress;
 * import java.net.UnknownHostException;
 *
 * @Component
 * public class ServerConfig  implements ApplicationListener<WebServerInitializedEvent> {
 *     private int serverPort;
 *
 *     public String getUrl() {
 *         InetAddress address = null;
 *         try {
 *             address = InetAddress.getLocalHost();
 *         } catch (UnknownHostException e) {
 *             e.printStackTrace();
 *         }
 *         return "http://"+address.getHostAddress() +":"+this.serverPort;
 *     }
 *
 *     @Override
 *     public void onApplicationEvent(WebServerInitializedEvent event) {
 *         this.serverPort = event.getWebServer().getPort();
 *     }
 *
 * }
 */
@Component
public class ServerConfig implements ApplicationListener<EmbeddedServletContainerInitializedEvent> {

    private int serverPort;

    public int getPort() {
        return this.serverPort;
    }

    @Override
    public void onApplicationEvent(EmbeddedServletContainerInitializedEvent event) {
        this.serverPort = event.getEmbeddedServletContainer().getPort();
    }
}